<template>
  <div class="approval_list">
    <div class="workVisit_con">
      <div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="我发起的" name="first"></el-tab-pane>
          <el-tab-pane label="我处理的" name="second"></el-tab-pane>
        </el-tabs>
      </div>

      <div class="search_con">
        <div class="search_item">
          <el-select
            v-model="type"
            clearable
            placeholder="请选择业务类型"
            size="small"
          >
            <el-option
              v-for="(item,index) in typeList"
              :key="index"
              :label="item.Value"
              :value="item.Key"
            >
            </el-option>
          </el-select>
        </div>
        <div class="search_item">
          <el-select
            v-if="activeName=='first'"
            v-model="state"
            clearable
            placeholder="请选择流程状态"
            size="small"
          >
            <el-option
              v-for="(item,index) in stateList"
              :key="index"
              :label="item.Value"
              :value="item.Key"
            >
            </el-option>
          </el-select>
          <el-select
            v-else
            v-model="estate"
            clearable
            placeholder="请选择流程状态"
            size="small"
          >
            <el-option
              v-for="(item,index) in exeStateList"
              :key="index"
              :label="item.Value"
              :value="item.Key"
            >
            </el-option>
          </el-select>
        </div>
        <div class="search_item">
          <el-date-picker
            v-model="value1"
            type="daterange"
            clearable
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
          >
          </el-date-picker>
        </div>
        <div class="search_item">
          <el-input
            v-model="input"
            clearable
            size="small"
            placeholder="请输入关键字"
          ></el-input>
        </div>
        <div class="btns search_item">
          <el-button type="primary" size="small" @click="getSeachList()"
          >搜索
          </el-button>
          <el-button size="small" @click="resetSeachList">重置</el-button>
        </div>
      </div>
      <div class="workVisit_table">
        <template>
          <el-table
            :data="tableData"
            size="medium"
            @cell-click="toDetail"
            border
            style="width: 100%"
          >
            <el-table-column
              prop="SerialNumber"
              label="流程编号"
              align="center"
              width="150"
            >
            </el-table-column>
            <el-table-column
              prop="FlowValue"
              label="业务类型"
              align="center"
              width="150"
            >
              <template slot-scope="scope">
                <span>{{ typeMap[scope.row.Flow.Code] }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="Template.Abstract"
              label="信息摘要"
              className="text-left"
              align="left"
              header-align="center"

            >
            </el-table-column>
            <el-table-column
              prop="CreatedAt"
              label="发起时间"
              align="center"
              width="170"
            >
            </el-table-column>
            <el-table-column
              v-if="activeName == 'first'"
              prop="StateTime"
              label="最后处理时间"
              width="170"
              align="center"
            >
            </el-table-column>
            <el-table-column
              v-if="activeName === 'second'"
              prop="Creator.Name"
              label="发起人"
              align="center"
              width="100"
            >
            </el-table-column>
            <el-table-column
              v-if="activeName === 'second'"
              prop="NextTime"
              label="进入本步骤时间"
              align="center"
              width="170"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.exe">{{
                  scope.row.exe.StartTime | timeStr
                }}</span>
                <span v-else-if="scope.row.next">{{
                  scope.row.next.StartTime | timeStr
                }}</span>
                <div style="color: red">{{residenceTime(scope.row)}}</div>
              </template>
            </el-table-column>
            <el-table-column
              v-if="activeName == 'second'"
              prop="StateTime"
              label="处理时间"
              width="170"
              align="center"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.exe">{{
                  scope.row.exe.StateTime | timeStr
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="StateValue"
              align="center"
              width="150"
              label="状态"
            >
              <template slot-scope="scope">
                <span v-if="activeName !== 'second'">{{
                  stateMap[scope.row.State]
                }}</span>
                <span v-else-if="scope.row.next">待处理</span>
                <span v-else-if="scope.row.exe && scope.row.exe.State=='Reject'">已处理
                  <div>[驳回]</div>
                </span>
                <span v-else-if="scope.row.exe && scope.row.exe.State=='Refuse'">已处理
                  <div>[拒绝]</div>
                </span>
                <span v-else>已处理
                  <div>[同意]</div>
                </span>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              align="center"
              width="120"
            >
              <template slot-scope="scope">
                <approval
                  :affair.sync="scope.row"
                  :tps="tps"
                  :is-text="true"
                  @toEdit="edit"
                ></approval>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
      <div class="pager-con">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage4"
          :page-sizes="[20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          :page-size="page.Size"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
    import {dateFormat1} from "../../utils/ruoyi";
    import approval from "@/components/approval/approvalList";
    import {
        getMyApproval,
        getMyCreated,
        getStateMap,
    } from "@/api/warehouse/approve/index.js";
    import { FlowAffairMap } from "@/api/approval/index";
    import { parseTime } from "@/utils/index.js";
    export default {
        name: "index",

        props: {
            typeList: {
                type: Array,
                required: true,
                default: function () {
                    return [];
                },
            },
        },
        filters: {
            timeStr(value) {
                if (!value) {
                    return "";
                }
                //return parseTime(value, "{y}-{m}-{d} {h}:{i}:{s}");
                value = value.replace('T'," ")
                return dateFormat1("yyyy-mm-dd HH:MM:SS",value)

            },
        },
        watch:{
            typeList:{
                handler(newV,oldV){
                    for (var item of this.typeList) {
                        this.typeMap[item.Key] = item.Value
                    }
                    this.getList()
                },
                deep:true
            }
        },

        data() {
            return {
                activeName: "first",
                typeMap: {},
                stateList: [],
                exeStateList: [],
                stateMap: [],
                stateValueList: [],
                type: "",
                state: "",
                estate:"",
                value1: [], //时间
                input: "",
                page: {
                    total: 0,
                    Index: 1,
                    Size: 20,
                },
                tableData: [],
                user: {},
                currentPage4: 1,

                dialogVisible1: false,
                destroyInfo: {},
                form: {
                    YesOrNo: "1",
                    textarea: "",
                },
                tps: {},
            };
        },
        components: { approval },
        created() {
            this.user = {Id:this.$store.getters.userInfo.user.id}
            this.getFlowAffairMap();
            this.getCheckplanMap().then((res) => {
                //this.getList();
            });
            for (var item of this.typeList) {
                this.typeMap[item.Key] = item.Value;
            }
        },
        mounted() {},
        methods: {
            getCheckplanMap() {
                return new Promise((r, c) => {
                    getStateMap().then((res) => {
                        if (res.state === 1) {
                            this.stateValueList.splice(
                                0,
                                this.stateValueList.length,
                                ...res.data.FlowState
                            );
                            this.stateList.splice(0, this.stateList.length, ...res.data.FindFlowState);
                            this.exeStateList.splice(0,this.exeStateList.length,...res.data.FindExecutorState)
                            for (var item of this.stateValueList) {
                                this.$set(this.stateMap, item.Key, item.Value);
                            }
                            r();
                        } else {
                            c();
                        }
                    });
                });
            },
            handleClick(tab, event) {
                console.log(tab, event);
                this.resetSeachList()
            },
            getFlowAffairMap() {
                FlowAffairMap().then((res) => {
                    this.tps = res.data;
                });
            },
            getList() {
                let list = [];
                for (let i = 0; i < this.typeList.length; i++) {
                    if (!this.type || this.type === this.typeList[i].Key) {
                        let item = {
                            Type: "Customize",
                            Code: this.typeList[i].Key,
                        };
                        list.push(item);
                    }
                }
                let start = null;
                let end = null;
                if (this.value1 && this.value1.length>0) {
                    start = this.value1[0];
                    end = new Date(this.value1[1].getTime()+24*60*60*1000-1);
                }
                let data = {
                    Index: this.page.Index,
                    Size: this.page.Size,
                    Type: list,
                    StartTime: start,
                    EndTime: end,
                    Key: this.input,
                };
                if (this.activeName === "first") {
                    data.State=this.state
                    getMyCreated(data).then((res) => {
                        if (res.state === 1) {
                            this.page.total = res.data.total;
                            if (!res.data.datas) {
                                res.data.datas = [];
                            }
                            let list = res.data.datas;
                            if (list && list.length) {
                                this.processingData(list);
                            }
                            this.tableData.splice(0, this.tableData.length);
                            this.tableData.push(...list);
                        }
                    });
                } else if (this.activeName === "second") {
                    data.State = this.estate
                    getMyApproval(data).then((res) => {
                        if (res.state === 1) {
                            this.page.total = res.data.total;
                            if (!res.data.datas) {
                                this.$set(res.data, "datas", []);
                            }
                            let list = res.data.datas;
                            if (list && list.length) {
                                this.processingData(list);
                            }
                            this.getExe(list);
                            this.tableData.splice(0, this.tableData.length);
                            this.tableData.push(...list);
                        }
                    });
                }
            },
            getExe(list) {
                for (var item of list) {
                    let has = false;
                    if (item.Next) {
                        for (var exe of item.Next) {
                            if (exe.Staffs.indexOf(this.user.Id) >= 0) {
                                has = true;
                                this.$set(item, "next", exe);
                                break;
                            }
                        }
                    }
                    if (!has && item.Executors) {
                        for (let i = item.Executors.length - 1; i >= 0; i--) {
                            let exe = item.Executors[i];
                            if (exe.StaffId == this.user.Id) {
                                this.$set(item, "exe", exe);
                                break;
                            }
                        }
                    }
                }
            },
            processingData(list) {
                for (let i = 0; i < list.length; i++) {
                    list[i].CreatedAt = this.formatTime(list[i].CreatedAt, "time");
                    list[i].StateTime = this.formatTime(list[i].StateTime, "time");
                    if (list[i].Next && list[i].Next.length) {
                        list[i].NextTime = this.formatTime(list[i].Next[0].StartTime, "time");
                    }
                }
            },
            toDetail(row, column, cell, event) {
                this.$emit("toDetail", row);
            },
            edit(row) {
                this.$emit("toEdit", row);
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.page.Index = val;
                this.currentPage4 = Number(this.page.Index);
                this.getList();
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.page.Size = val;
                this.getList();
            },
            // 搜索
            getSeachList(){
                this.page.Index = 1;
                this.currentPage4 = Number(this.page.Index);
                this.getList();
            },
            //重置
            resetSeachList() {
                // 重置
                this.type = "";
                this.page.total=0
                this.page.Index =1
                this.page.Size = 20
                this.currentPage4 = 1;
                this.value1 = [];
                this.input = "";
                this.state = "";
                this.estate=""
                this.getList();
            },
            handleClose(done) {
                this.$confirm("确认关闭？")
                    .then((_) => {
                        done();
                    })
                    .catch((_) => {});
            },
            formatTime(time, type) {
                var date = time;
                if (typeof time != "date") {
                    date = new Date(time);
                }
                var Y = date.getFullYear();
                var M =
                    date.getMonth() + 1 < 10
                        ? "0" + (date.getMonth() + 1)
                        : date.getMonth() + 1;
                var D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
                var h = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
                var m =
                    date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
                var s =
                    date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
                if (type === "date") {
                    return Y + "-" + M + "-" + D;
                } else if (type === "time") {
                    return Y + "-" + M + "-" + D + " " + h + ":" + m + ":" + s;
                }
            },
            residenceTime: function(row) {
                let str = ''
                if (row.State != 'Done' && row.State != 'Refuse') {
                    if (row.Next && row.Next.length) {
                        let index = row.Next.findIndex(a => {
                            return a.Staffs.findIndex(b => b == this.$store.getters.userInfo.user.id) != -1
                        })
                        if (index != -1) {
                            let data = row.Next[index]

                            let date = new Date(data.StartTime)
                            let date1 = new Date()
                            let time = date1.getTime() - date.getTime()
                            let day = 60 * 60 * 24 * 1000

                            if (time > day) {
                                str = '(滞留' + (time / day).toFixed(0) + '天)'
                            }
                        }
                    }
                }

                return str
            },
        },
    };
</script>
<style lang="scss" scoped>
  @import "@/assets/scss/components/approval/main.scss";
  .flex {
    display: flex;
  }

  .flex_seach {
    margin-right: 20px;
  }
</style>
